package com.yuedou.jylt.http

import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import com.alibaba.fastjson.JSONObject
import okhttp3.*
import java.io.InputStream
import java.util.concurrent.Executor
import java.util.concurrent.Executors

/**
 * Created by 俊华 on 17/8/12.
 */
object NetUtils {

    private var client: OkHttpClient
    private var mHandler: Handler
    private var threadPool: Executor
    private lateinit var newCallBack: NewCallBack<Any>
    private lateinit var url: String
    private var params: Map<String, String>? = null
    private lateinit var request: Request


    init {
        client = OkHttpClient()
        mHandler = Handler(Looper.getMainLooper())
        threadPool = Executors.newCachedThreadPool()
    }
    /**
     * get请求
     */
    fun <T> getHttp(url: String?, params: Map<String, String>?, callBack: NewCallBack<T>) {
        http(url, params, false, callBack)
    }
    /**
     * post请求
     */
    fun <T> postHttp(url: String?, params: Map<String, String>?, callBack: NewCallBack<T>) {
        http(url, params, true, callBack)
    }

    private fun <T> http(url: String?, params: Map<String, String>?, isPost: Boolean, callBack: NewCallBack<T>) {
        if (TextUtils.isEmpty(url)) {
            Log.e("url", "你输入的路径为空")
        } else {
            this.url = url as String
            this.params = params
            this.newCallBack = callBack as NewCallBack<Any>
            setRequest(isPost)
            runOnNet()
        }
    }


    /**
     * 处理自定义的类
     */
    fun <T> parseJsonWithFast(jsonData: String, type: Class<T>?): T? {
        if (TextUtils.isEmpty(jsonData)) {
            return null
        }
        try {
            Log.e("数据类型为自定义", "parseJsonWithFast()")
            return JSONObject.parseObject(jsonData, type)
        } catch (e: Exception) {
            Log.e("fastJson解析数据异常", e.toString())
            return null
        }
    }

    private fun setRequest(isPost: Boolean) {
        if (params != null) {
            if (isPost) {
                val requestBody = MultipartBody.Builder()
                requestBody.setType(MultipartBody.FORM)
                val iterator = params!!.entries.iterator()
                while (iterator.hasNext()) {
                    val entry = iterator.next()
                    requestBody.addFormDataPart(entry.key, entry.value)
                }
                request = Request.Builder().url(url).post(requestBody.build()).build()
            } else {
                val urlStr = url + "?" + MapParamToString(params!!)
                request = Request.Builder().url(urlStr).build()
            }

        } else {
            request = Request.Builder().url(url).build()
        }
    }
    /**
     *处理传入的请求参数
     */
    private fun MapParamToString(params: Map<String, String>): String {
        if (params != null) {
            val stringBuilder = StringBuilder()
            val iterator = params.entries.iterator()
            while (iterator.hasNext()) {
                val entry = iterator.next()
                stringBuilder.append(entry.key + "=" + entry.value + "&")
            }
            val str = stringBuilder.toString().substring(0, stringBuilder.length - 1)
            return str
        }
        return ""
    }

    private fun runOnNet() {
        threadPool.execute {
//            client.newCall(request).enqueue(object : Callback {
//                override fun onFailure(call: Call?, e: IOException?) {
//                    mHandler.post {
//                        newCallBack.onFail("请求失败")
//                    }
//                }
//
//                override fun onResponse(call: Call?, response: Response?) {
//                    if (response != null) {
//                        if (response.isSuccessful) {
//                            when (newCallBack.Type()!!.simpleName) {
//                                "String" -> dealString(response.body()!!.string())
//                                //将响应数据转化为输入流数据
//                                "Bitmap" -> dealBitmip(response.body()!!.byteStream())
//                                else -> dealClazz(response.body()!!.string())
//                            }
//                        } else {
//                            onError("请求失败")
//                        }
//                    } else {
//                        onError("解析错误")
//                    }
//                }
//            })
        }
    }

    /**
     * 处理图片
     */
    private fun dealBitmip(inputStream: InputStream) {

        //将输入流数据转化为Bitmap位图数据
        val bitmap = BitmapFactory.decodeStream(inputStream)
        if (bitmap != null) {
            mHandler.post({
                newCallBack.onSuccess(bitmap)
            })
        } else {
            onError("转换图片失败")
        }
    }

    /**
     * 返回字符串
     */
    private fun dealString(res: String?) {
        if (res != null) {
            if (!TextUtils.isEmpty(res)) {
                mHandler.post({
                    newCallBack.onSuccess(res)
                })
            } else {
                onError("解析错误")
            }
        } else {
            onError("解析错误")
        }
    }

    /**
     * 返回错误提示
     */
    private fun onError(err: String) {
        mHandler.post({
            newCallBack.onFail(err)
        })
    }

    /**
     * 处理自定义类型
     */
    private fun dealClazz(res: String) {
        val any = parseJsonWithFast(res, newCallBack.Type())
        if (any != null) {
            mHandler.post {
                newCallBack.onSuccess(any)
            }
        } else {
            onError("解析失败")
        }


    }
}